﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Threading;

namespace WatiN.Samples.Console
{
    public class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            System.Console.WriteLine("校内网之抢车位V0.1d, by tony2u 2008.11.24(http://code.google.com/p/xiaoneiwg/)\n");
            Program program = new Program();
            Program.ReadGlobalConfig();

            while (_repeatTime > 0)
            {
                int restTime = _repeatTime;
                string[] filelist = Directory.GetFiles(_appDirectory, "*.ini");
                Array.Sort(filelist);

                // XiaoNei website
                foreach (string filename in filelist)
                {
                    UserConfigData userConfig = ConfigHelper.ReadUserConfigData(filename);
                    int tryTimes = _config.TryTimes;
                    while (tryTimes-- > 0)
                    {
                        try
                        {
                            if (program.Run(userConfig))
                                break;
                        } 
                        catch (Exception e)
                        {
                            System.Console.WriteLine(e.Message);
                            System.Console.WriteLine(e.StackTrace);
                        }
                    }
                }
                while (restTime > 0)
                {
                    TraceLog.PrintLn("Wait {0} mins to restart...", restTime--);
                    Thread.Sleep(60 * 1000);
                }
            }
        }

        /// <summary>
        /// Do car park
        /// </summary>
        /// <param name="config"></param>
        public bool Run(UserConfigData config)
        {
            string content = String.Empty;

            //Step-1: login
            string email = config.Email;
            string password = config.Password;
            content = _hh.Post("http://login.xiaonei.com/Login.do", "email=" + HttpHelper.EncodePostData(email) + 
                "&password=" + HttpHelper.EncodePostData(password) + "&origURL=http%3A%2F%2Fwww.xiaonei.com%2FSysHome.do");
            if (content.IndexOf("<title>校内 - ") != -1)
            {
                TraceLog.PrintLn("登录" +  email + "成功!");
            }
            else
            {
                TraceLog.Error("登录" + email + "失败!");
                return false;
            }
            Thread.Sleep(ConfigHelper.SLEEP_TIME);

            //Step-2: car parking
            //ie.Link(Find.ByUrl("http://apps.xiaonei.com/carpark/")).Click();
            content = _hh.Get("http://apps.xiaonei.com/carpark/");
            if (content.IndexOf("<title>校内网</title>") != -1)
            {
                TraceLog.PrintLn("成功跳转到抢车位的链接!");
            }
            else
            {
                TraceLog.Error("不能打开抢车位的链接!");
                return false;
            }

            ParkerContent pct = new ParkerContent();
            pct.GetFriendList(content);
            TraceLog.PrintLn(String.Format("获取{0}({1})的信息: 现金:{2} 元!", "主人", pct._ownerId, pct._ownerMoney));

            content = _hh.Get("http://carpark.xiaonei.com/ajaxGetMyCar.f");
            TraceLog.PrintLn("获取自己的车辆信息!");
            pct.GetCarlist(content);

            if (config.DoParking)
            {
                foreach (CarInfo car in pct._carInfoList)
                {
                    pct.DoParking(car, _hh);
                }
            }

            if (config.DoPost)
            {
                pct.DoPost(_hh);
            }

            TraceLog.Print("退出: ");
            _hh.Get("http://www.xiaonei.com/Logout.do");
            TraceLog.PrintLn("Ok!\n");

            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        private static void ReadGlobalConfig()
        {
            string filename = _appDirectory + Path.DirectorySeparatorChar + CONFIG_FILENAME;

            if (!File.Exists(filename))
            {
                TraceLog.PrintLn("缺少{0}文件，系统加载默认配置.", filename);
                return;
            }

            _config = ConfigHelper.ReadGlobalConfigData(filename);
            _repeatTime = _config.RepeatTime;
        }

        #region Member Fields
        private const string CONFIG_FILENAME = "Config.txt";
        private static string _appDirectory = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        private static GlobalConfigData _config = new GlobalConfigData();
        private HttpHelper _hh = new HttpHelper();
        private static int _repeatTime = -1;
        #endregion
    }
}
